package com.ict.ms.artificial.service.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;

public class MQTopicPublish_Artificial {
    private static String IP,user,password,EXCHANGE_NAME;
    private static String EXCHANGE_TYPE = "topic";
    private static boolean EXCHANGE_DURABLE = true;

    private Connection connection;
    private Channel channel;

    public MQTopicPublish_Artificial(String IP, String user, String password, String EXCHANGE_NAME){
        this.IP = IP;
        this.user = user;
        this.password = password;
        this.EXCHANGE_NAME = EXCHANGE_NAME;

//        BaseConnection();
    }

    /**
     * 发布消息
     * @param routingKey routingKey
     * @param msg 消息
     * @return
     */
    public boolean Publish(String routingKey,byte[] msg){
            try {
                channel.basicPublish(EXCHANGE_NAME,routingKey,null,msg);
                System.out.println("[x] Sender Sent " + routingKey + " : " + msg);

                finalize();
                return true;
            } catch (IOException e) {
                System.out.println("[y] Sender failed to basic publish.");

                finalize();
                return false;
            }
    }

    public void finalize(){
        try {
            channel.close();
            connection.close();
            System.out.println("RabbitMQ channel、connection 关闭成功");
        }catch (Exception e){
            System.out.println("RabbitMQ关闭异常");
        }
    }

    public int BaseConnection(int port){
        /**
         * 创建连接连接到RabbitMQ
         */
        ConnectionFactory factory = new ConnectionFactory();
        //设置MabbitMQ所在主机ip或者主机名
        factory.setHost(IP);
        factory.setPort(port);
        factory.setUsername(user);
        factory.setPassword(password);

        //创建一个连接
        try {
            connection = factory.newConnection();
        } catch (IOException e) {
            System.out.println("[x] 请确认输入的IP地址、用户名、密码是否准确！");
            return  -1;
        } catch (Exception e) {
            System.out.println("[x] 连接RabbitMQ超时，请重试！");
            return  -1;
        }

        //创建一个频道
        try {
            channel = connection.createChannel();
        } catch (IOException e) {
            System.out.println("[x] 创建频道出错，请重试！");
            return -1;
        }

        //声明一个路由器，指定名称、模式、及其是否durable
        try {
            channel.exchangeDeclare(EXCHANGE_NAME,EXCHANGE_TYPE,EXCHANGE_DURABLE);
        } catch (IOException e) {
            System.out.println("[x] 路由器声明失败，请重试！");
            return -1;
        }

        System.out.println("[x] 发布消息者成功连接至RabbitMQ !");
        return 0;
    }
}
